package com.hanlin.backend.config;

import cn.hutool.core.util.StrUtil;
import com.hanlin.backend.common.entity.HlUser;
import com.hanlin.backend.common.util.JwtToken;
import com.hanlin.backend.common.util.JwtUtil;
import com.hanlin.backend.service.HlUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * shiro权限认证
 *
 * @author:hl.yuan
 * @date：2020-12-22
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private HlUserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 获取用户角色和权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("进入授权界面");
        return null;
    }

    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 得到jwt的token
        String token = (String) authenticationToken.getCredentials();
        // 解密出name
        String username = JwtUtil.getUsername(token);
        if (StrUtil.isBlank(username)) {
            throw new AuthenticationException("token校验不通过");
        }
        HlUser user = userService.findByUserName(username);
        if (user == null) {
            throw new AuthenticationException("用户名或密码错误");
        }
        if (!JwtUtil.verify(token, username, user.getPassword())) {
            throw new AuthenticationException("token校验不通过");
        }
        return new SimpleAuthenticationInfo(token, token, "shiro_realm");
    }
}
